package com.sxdx.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Query;
import org.springframework.stereotype.Service;
import com.sxdx.dao.MydateDAO;
import com.sxdx.entity.Mydate;
import com.sxdx.service.MydateService;
import com.sxdx.util.DateUtil;

@SuppressWarnings("all")
@Service("mydateService")
public class MydateServiceImpl implements MydateService {
	private static Logger logger = LogManager.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());
	@Resource(name = "mydateDAO")
	private MydateDAO mydateDAO;

	public void insureStartime(String begin, String times) {
		int num = Integer.parseInt(times);
		try {
			Calendar cal = DateUtil.stringToCalendar(begin, "yyyy-MM-dd");
			int start = DateUtil.getWeekOfYear(begin);
			Mydate mydate = null;
			for (int i = 0; i < num; i++) {
				mydate = new Mydate();
				mydate.setDate(DateUtil.calendarToString(cal, "yyyy-MM-dd"));
				int cur = DateUtil.getWeekOfYear(DateUtil.calendarToString(cal, "yyyy-MM-dd"));
				// int myweek = (cur-start)>=1?(cur-start):0;
				int myweek = 0;
				if (cur - start >= 1) {
					myweek = cur - start;
				}
				if (cur - start < 0) {
					myweek = cur - start + 52; // 考虑到跨年
				}
				if (cur - start == 0) {
					myweek = 0;
				}
				mydate.setMyweek(myweek);
				int dayofweek = DateUtil.getDayOfWeek(DateUtil.calendarToString(cal, "yyyy-MM-dd"));
				mydate.setDayofweek(dayofweek);
				int weekofyear = DateUtil.getWeekOfYear(DateUtil.calendarToString(cal, "yyyy-MM-dd"));
				mydate.setWeekofyear(weekofyear);
				int weekofmonth = DateUtil.getWeekOfMonth(DateUtil.calendarToString(cal, "yyyy-MM-dd"));
				mydate.setWeekofmonth(weekofmonth);
				mydateDAO.save(mydate);
				cal.add(Calendar.DATE, 1);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	public void resetdate() {
		String hql = "from Mydate";
		List<Mydate> mydates = mydateDAO.find(hql);
		for (Mydate mydate : mydates) {
			mydateDAO.delete(mydate);
		}
	}

	public List<Object> getmyweek() {
		String sql = "select o.myweek from mydate o group by o.myweek";
		Query query = mydateDAO.findBySql(sql);
		return query.list();
	}

	public List<Mydate> getDate(int weektype, int dayofweek) {
		String hql = "from Mydate m where m.myweek=? and m.dayofweek=?";
		List<Object> param = new ArrayList<Object>();
		param.add(weektype);
		param.add(dayofweek);
		return mydateDAO.find(hql, param);
	}
}
